#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    static QString pathname = "";

    connect(ui->push_button_1, &QPushButton::clicked, this, [=]() {
        // 从文件对话框中获取文件的路径
        pathname = QFileDialog::getOpenFileName(this, "Select File", "D\\Desktop");
        ui->line_edit->setText(pathname);

        if (pathname != "") {
            // 以只读的方式打开选择的文件
            QFile file(pathname);
            file.open(QIODevice::ReadOnly);

            QByteArray array;
            // 一次性读取
            // array = file.readAll();
            // 按行多次读取
            while (!file.atEnd()) {
                array += file.readLine();
            }

            // 显示选择文件的全部信息
            ui->text_edit->setText(array);

            // 关闭文件操作
            file.close();
        }
    });


    connect(ui->push_button_2, &QPushButton::clicked, this, [=]() {
        if (pathname == "") {
             QMessageBox::warning(this, "Warning", "Please Select The File First!");
             return;
        }

        QFile file(pathname);
        file.open(QIODevice::WriteOnly);

        // 暂时处理不了非纯文本的内容
        QString string = ui->text_edit->toPlainText();
        file.write(string.toUtf8());

        // 关闭文件操作
        file.close();
    });
}

Widget::~Widget()
{
    delete ui;
}

